package io.mft.runtime.function.combination;

import java.util.List;

import io.mft.api.domain.Api;
import io.mft.api.domain.ApiFunctionType;
import io.mft.api.domain.ApiRegulation;
import io.mft.api.domain.RegulationProcessClassify;
import io.mft.commons.exception.MFTException;
import io.mft.flow.core.FlowExecutor;
import io.mft.flow.core.executable.ConditionType;
import io.mft.flow.core.executable.ExecutableType;
import io.mft.flow.core.executable.builder.ChainBuilder;
import io.mft.flow.core.executable.drive.ChainConditionDriver;
import io.mft.flow.core.executable.drive.ConditionDriverType;
import io.mft.runtime.function.FlowRegister;
/**
 * 接口编排配置解析器
 * @说明：TODO
 * @类型名称：ApiFunctionExecutorFlowRegister
 * @创建者: 胡常建  
 * @创建时间: 2021年2月21日 上午10:04:11
 * @修改者: 胡常建  
 * @修改时间: 2021年2月21日 上午10:04:11
 */
public class ApiFunctionExecutorFlowRegister implements FlowRegister {
	
	private FlowExecutor flowExecutor;
	public ApiFunctionExecutorFlowRegister(FlowExecutor flowExecutor) {
		this.flowExecutor=flowExecutor;
	}
	
	@Override
	public void register(Api api,boolean isReload) {
		if (api.getApiFunctionType() == ApiFunctionType.combination) {
			ChainBuilder builder=new ChainBuilder(api.getKey(), flowExecutor);
			List<ApiRegulation> apiRegulations=api.getApiRegulations();
			apiRegulations.forEach(r->{
				ConditionDriverType conditionDriverType=ConditionDriverType.valueOf(r.getRegulation().getChainConditionDriver());
				String[] nodeIds=r.getRegulation().getValue().split(",");
				ChainConditionDriver driver=conditionDriverType.chainConditionDriver();
				ConditionType conditionType=convertConditionType(r.getRegulation().getProcessClassify());
				builder.addChainConditionExecutable(ExecutableType.CHAIN,conditionType, r.getPos(), driver, nodeIds);
			});
			builder.build().addToFlowExecutor(isReload);
		}
	}
	private ConditionType convertConditionType(RegulationProcessClassify processClassify) {
		switch (processClassify) {
		case async:
			return ConditionType.async;
		case sync:
			return ConditionType.sync;
		case syncWaitAsync:
			return ConditionType.syncWaitAsync;
		case flowPredictate:
			return ConditionType.sync;		
		default:
			throw new MFTException("不支持的flow编排类型["+processClassify.name()+"],请检查");
		}
	}
	@Override
	public void unregister(String apiKey) {
		// TODO Auto-generated method stub
		
	}
}
